package top.flvio.middleware.strategy.impl;




import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.flvio.middleware.DBContextHolder;
import top.flvio.middleware.DBRouterConfig;
import top.flvio.middleware.strategy.IDBRouterStrategy;

/**
 * @description: 哈希路由
 * @author: flvio
 * @date: 2025/2/3
 */
public class DBRouterStrategyHashCode implements IDBRouterStrategy
{
    private Logger logger = LoggerFactory.getLogger(DBRouterStrategyHashCode.class);

    private DBRouterConfig dbRouterConfig;

    public DBRouterStrategyHashCode(DBRouterConfig dbRouterConfig)
    {
        this.dbRouterConfig = dbRouterConfig;
    }

    @Override
    public void doRouter(String dbKeyAttr)
    {
        int size = dbRouterConfig.getDbCount() * dbRouterConfig.getTbCount();

        //扰动函数
        int idx = (size - 1) & (dbKeyAttr.hashCode() ^ (dbKeyAttr.hashCode() >>> 16));

        //库表索引
        int dbIdx = idx / dbRouterConfig.getTbCount() + 1;
        int tbIdx = idx - dbRouterConfig.getTbCount() * (dbIdx - 1);

        setDBKey(dbIdx);
        setTBKey(tbIdx);

    }

    @Override
    public void setDBKey(int dbIdx)
    {
        DBContextHolder.setDbKey(String.format("%02d",dbIdx));
    }

    @Override
    public void setTBKey(int tbIdx)
    {
        DBContextHolder.setTbKey(String.format("%03d",tbIdx));
    }

    @Override
    public int dbCount()
    {
        return dbRouterConfig.getDbCount();
    }

    @Override
    public int tbCount()
    {
        return dbRouterConfig.getTbCount();
    }

    @Override
    public void clear()
    {
        DBContextHolder.clearDBKey();
        DBContextHolder.clearTBKey();
    }
}
